/**
 * 商城首页控制器
 */
angular.module('homes.controller', ['homes.service'])
  .controller('HomeCtrl', function ($scope, $window, HomeFty) {
    // $scope.$on('$ionicView.enter', function (e) {

      goTop();
      countdown();
      headerChangeColor();

      getShopCategory();
    // });
    // console.log(HomeFty);


    // console.log(HomeFty.getShopCategory());
    function getShopCategory() {
      var promise = HomeFty.getShopCategory();
      // console.log(promise)
      promise.then(
        // 成功的回调函数
        function (data) {
          if (data) {
            $scope.ShopCategory = data;
            console.log(data)
          }
        });
    }



    // 改变头部搜索区域的颜色
    function headerChangeColor() {
      var bg = window.document.getElementById('home-content');
      var nowOpacity = 0;
      bg.onscroll = function (event) {
        // console.log(this.scrollTop / 250);
        if (this.scrollTop / 250 < 1) {
          nowOpacity = this.scrollTop / 250;
        }
        document.getElementById("headerBar-bg").style.opacity = nowOpacity;
      }
    }
    //回到顶部
    function goTop() {
      var bg = window.document.getElementById('home-content');
      var goTop = document.querySelector(".back_top");

      bg.addEventListener('scroll', function () {
        var top = bg.scrollTop;
        if (top > 200) {
          goTop.style.opacity = 1;
        } else {
          goTop.style.opacity = 0;
        }
      }, false);

      goTop.onclick = function () {
        bg.scrollTop = 0;
      }
    };
    // 秒杀计时器
    function countdown() {
      if ($window.timer) {
        clearInterval($window.timer);
      }
      // 倒计时
      var timeObj = {
        h: 1,
        m: 37,
        s: 13
      };
      var timeStr = toDouble(timeObj.h) + toDouble(timeObj.m) + toDouble(timeObj.s);
      var timeList = document.getElementsByClassName('time-text');
      for (var i = 0; i < timeList.length; i++) {
        timeList[i].innerHTML = timeStr[i];
      }
      function toDouble(num) {
        if (num < 10) {
          return '0' + num;
        } else {
          return '' + num;
        }
      }
      $window.timer = setInterval(function () {
        timeObj.s--;
        if (timeObj.s == -1) {
          timeObj.m--;
          timeObj.s = 59;
        }
        if (timeObj.m == -1) {
          timeObj.h--;
          timeObj.m = 59;
        }
        if (timeObj.h == -1) {
          timeObj.h = 0;
          timeObj.m = 0;
          timeObj.s = 0;
          clearInterval($window.timer);
        }
        timeStr = toDouble(timeObj.h) + toDouble(timeObj.m) + toDouble(timeObj.s);
        for (var i = 0; i < timeList.length; i++) {
          timeList[i].innerHTML = timeStr[i];
        }
      }, 1000);
    };

  });
